<template>
    <div>
        <div class="container">
            <el-form ref="form" :model="form" :rules="rules" label-width="100px">
                <el-form-item label="名称：">
                    <el-input class="w" v-model="form.name"></el-input>
                </el-form-item>

                <el-form-item label="歌单数量：" prop="playListNum">
                    <el-input class="w" v-model="form.playListNum"></el-input>
                </el-form-item>

                <el-form-item label="歌曲数量：" prop="songNum">
                    <el-input class="w" v-model="form.songNum"></el-input>
                </el-form-item>

                <el-form-item label="类型：" prop="playlistType">
                    <el-select :clearable="true" v-model="form.playlistType" placeholder="请选择歌单类型" class="handle-select mr10 w">
                        <el-option key="0" label="歌单" :value="0"></el-option>
                        <el-option key="1" label="电台" :value="1"></el-option>
                        <el-option key="2" label="榜单" :value="2"></el-option>
                    </el-select>
                </el-form-item>

                <!-- <el-form-item label="风格：">
                    <el-select :clearable="true" v-model="form.genre" placeholder="请选择风格" class="handle-select mr10 w" multiple>
                        <el-option v-for="(item, index) in genres_1" :key="index" :label="item.label" :value="item.value"></el-option>
                    </el-select>
                </el-form-item> -->

                <!-- <el-form-item label="一级分类：">
                    <el-select :clearable="true" v-model="form.Lv1" placeholder="请选择分类" class="handle-select mr10 w">
                        <el-option v-for="(item, index) in options" :key="index" :label="item.label" :value="item.value"></el-option>
                    </el-select>
                </el-form-item> -->

                <el-form-item label="标签：">
                    <div class="block">
                        <el-cascader
                            :show-all-levels="false"
                            v-model="form.tags"
                            class="w"
                            :options="tagList"
                            :props="{
                                emitPath: false,
                                multiple: true,
                                checkStrictly: true,
                                value: 'value',
                                label: 'label',
                                children: 'children'
                            }"
                            @change="handlechange"
                        >
                            <template slot-scope="{ node, data }">
                                <span>{{ data.label }}</span>
                                <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
                            </template>
                        </el-cascader>
                    </div>
                </el-form-item>

                <!-- <el-form-item label="二级分类：">
                    <el-select
                        v-el-select-loadmore:rangeNumber="loadMore(rangeNumber)"
                        :clearable="true"
                        v-model="form.Lv2"
                        placeholder="请选择分类"
                        class="handle-select mr10 w"
                        @visible-change="changeValue_($event)"
                    >
                        <el-input v-model="search" size="small" placeholder="请输入搜索内容"></el-input>
                        <el-option
                            v-for="(item, index) in list.slice(0, rangeNumber)"
                            :key="index"
                            :label="item.label"
                            :value="item.value"
                        ></el-option>
                    </el-select>
                </el-form-item> -->

                <el-form-item>
                    <el-button type="reset" @click="handleReset">查看日志</el-button>
                    <el-button
                        type="primary"
                        :disabled="
                            checkRequire({
                                playListNum: form.playListNum,
                                songNum: form.songNum,
                                playlistType: form.playlistType
                            })
                        "
                        @click="handleCreate"
                        >提交生成</el-button
                    >
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>

<script>
// import { genres_1 } from '@/components/common/';

import Vue from 'vue';
Vue.directive('el-select-loadmore', {
    bind(el, binding) {
        let self = this;
        // 获取element-ui定义好的scroll盒子
        let SELECTWRAP_DOM = el.querySelector('.el-select-dropdown .el-select-dropdown__wrap');
        SELECTWRAP_DOM.addEventListener('scroll', function() {
            /**
             * scrollHeight 获取元素内容高度(只读)
             * scrollTop 获取或者设置元素的偏移值,常用于, 计算滚动条的位置, 当一个元素的容器没有产生垂直方向的滚动条, 那它的scrollTop的值默认为0.
             * clientHeight 读取元素的可见高度(只读)
             * 如果元素滚动到底, 下面等式返回true, 没有则返回false:
             * ele.scrollHeight - ele.scrollTop === ele.clientHeight;
             */
            let condition = this.scrollHeight - this.scrollTop <= this.clientHeight;
            if (condition) binding.value();
        });
    }
});

export default {
    name: 'BatchMenu',
    data() {
        return {
            tagList: [],
            rules: {
                playListNum: [{ required: true, message: '请输入歌单数量', trigger: 'blur' }],
                songNum: [{ required: true, message: '请输入歌曲数量', trigger: 'blur' }],
                playlistType: [{ required: true, message: '请选择类型', trigger: 'change' }]
            },
            // genres_1,
            form: {
                name: '',
                playListNum: '',
                songNum: '',
                playlistType: '',
                tags: []
                // genre: '',
                // Lv1: '',
                // Lv2: ''
            },
            options: [],
            // options_: [],

            // list: [],
            rangeNumber: 10
            // search: ''
        };
    },
    watch: {
        // search(newVal, oldVal) {
        //     console.log(newVal);
        //     if (newVal) {
        //         this.list = this.options_;
        //         this.list = this.list.filter(item => {
        //             if (item.label.includes(newVal)) {
        //                 return item;
        //             }
        //         });
        //     } else {
        //         this.list = this.options_;
        //     }
        // }
    },
    activated() {
        this.getCates();
        this.getTagData();
    },
    methods: {
        handlechange(value) {},
        async getTagData() {
            try {
                let url = '/tag/tagAll';
                let { data: res } = await this.$http[2].get(url, {
                    params: {
                        type: 1
                    }
                });
                if (res.code != '0000') {
                    throw new Error(res.message);
                }

                if (res.data && res.data.length && res.data.length != 0) {
                    res.data.map(v => {
                        v.disabled = true;
                    });
                    var ret = this.formatData(res.data);

                    this.tagList = ret;
                } else {
                    this.tagList = [];
                }
            } catch (err) {
                console.dir(err);
                this.$message.error({
                    message: err.message,
                    duration: 1500
                });
            }
        },
        formatData(array) {
            for (let item of array) {
                item.value = item.id;
                item.label = item.description;
                item.children = [];

                delete item.type;
                delete item.createTime;
                delete item.description;
                delete item.groupId;
                delete item.id;
                delete item.name;
                delete item.status;
                delete item.updateTime;
                delete item.pid;

                if (item.tblTags && item.tblTags.length != 0) {
                    item.children = item.tblTags;

                    delete item.tblTags;
                    this.formatData(item.children);
                } else {
                    delete item.children;
                }
            }
            return array;
        },
        checkRequire(obj) {
            return this.$isEmpty(obj);
        },
        // changeValue_: function(bool) {
        //     console.log(bool);
        //     if (bool && this.list.length == 0) {
        //         this.list = this.options_;
        //     }
        // },
        loadMore(n) {
            console.log(n);
            // n是默认初始展示的条数会在渲染的时候就可以获取,具体可以打log查看
            // if(n < 8) this.rangeNumber = 10 //elementui下拉超过7条才会出滚动条,如果初始不出滚动条无法触发loadMore方法
            return () => (this.rangeNumber += 5); //每次滚动到底部可以新增条数  可自定义
        },

        getCates() {
            Promise.all([this.wake(1), this.wake(2)])
                .then(result => {
                    console.log('分类数据', result);
                    for (var i = 0; i < result.length; i++) {
                        if (result[i] && result[i].length && result[i].length > 0) {
                            if (i == 0) {
                                result[i].map(item => {
                                    this.options.push({
                                        label: item.name,
                                        value: item.id
                                    });
                                });
                            } else if (i == 1) {
                                // result[i].map(item => {
                                //     this.options_.push({
                                //         label: item.name,
                                //         value: item.id
                                //     });
                                // });
                                // this.list = this.options_;
                            }
                        } else {
                            this.options = [];
                            // this.options_ = [];
                            // this.list = this.options_;
                        }
                    }
                })
                .catch(error => {
                    console.log(error);
                });
        },
        wake(lvn) {
            return new Promise((resolve, reject) => {
                this.getLabel(lvn, resolve);
            });
        },
        async getLabel(lvn, resolve) {
            try {
                // let url = '/tag/getLvn';
                let url = '/tag/tagAll';
                let { data: res } = await this.$http[2].get(url, {
                    params: {
                        // lvn
                        type: 4
                    }
                });
                console.log(res);
                if (res.code != '0000') {
                    throw new Error(res.message);
                }
                resolve(res.data);
            } catch (err) {
                this.$message.error({
                    message: err.message,
                    duration: 1500
                });
            }
        },
        handleCreate() {
            this.$confirm('确定要提交吗？', '提示', {
                type: 'warning'
            })
                .then(() => {
                    this.create();
                })
                .catch(() => {});
        },
        async create() {
            try {
                let url = '/batch/beatchPlaylist';
                // var str = JSON.stringify(this.form.tags.join(','));
                // console.log(str);
                // var tagIds = str.substring(1, str.length - 1);
                // console.log(tagIds);

                let { data: res } = await this.$http[2].post(
                    url,
                    this.$removeField({
                        name: this.form.name,
                        playListNum: this.form.playListNum,
                        songNum: this.form.songNum,
                        playlistType: this.form.playlistType,
                        tagIds: this.form.tags
                        // genre: this.form.genre.join(','),
                        // v1: this.form.Lv1,
                        // v2: this.form.Lv2
                    })
                );
                this.$message.success({
                    message: res.message,
                    duration: 1500
                });
                // this.$router.replace({
                //     path: '/edit/menu'
                // });

                this.form = {
                    name: '',
                    playListNum: '',
                    songNum: '',
                    playlistType: '',
                    // genre: '',
                    Lv1: '',
                    Lv2: ''
                };
            } catch (err) {
                console.dir(err);
                this.$message.error({
                    message: err.message,
                    duration: 1500
                });
            }
        },
        handleReset() {}
    }
};
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    /* width: 120px; */
    width: 185px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}
.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mr10 {
    margin-right: 10px;
}
.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
.w {
    width: 470px;
}
</style>
